//
//  TabBarViewController.swift
//  DownloadTube
//
//  Created by Carlos on 20/11/14.
//  Copyright (c) 2014 Noname. All rights reserved.
//

import UIKit
import iAd

class TabBarViewController: UITabBarController {

    private let searchTabBarIndex = 0
    private let downloadTabBarIndex = 1
    private let storedTabBarIndex = 2
    private let indexTabBarIndex = 3
    
    private var numOfDownloadsNotSeen = 0
    private var numOfSavedVideosNotSeen = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "newDownload:", name:"NewDownload", object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "savedVideo:", name:"FinishedDownload", object: nil)
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

   func newDownload(notification:NSNotification) {

        if (super.selectedIndex != downloadTabBarIndex) {
    
            let downloadTabBarItem =  super.tabBar.items![downloadTabBarIndex] as UITabBarItem
            numOfDownloadsNotSeen++
            
            Async.main {
            
                downloadTabBarItem.badgeValue = String(format:"%d", self.numOfDownloadsNotSeen)
            }
        }
    }
    
    func savedVideo(notification:NSNotification) {
        
        if (super.selectedIndex != storedTabBarIndex) {
            
            let storedTabBarItem =  super.tabBar.items![storedTabBarIndex] as UITabBarItem
            numOfSavedVideosNotSeen++
            
            Async.main {
                
                storedTabBarItem.badgeValue = String(format:"%d", self.numOfSavedVideosNotSeen)
            }
        }
    }
    
    override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem!)  {
        
       let indexSelected =  (super.tabBar.items! as NSArray).indexOfObject(item)
        
        switch(indexSelected){
            
        case downloadTabBarIndex: numOfDownloadsNotSeen = 0
        case storedTabBarIndex: numOfSavedVideosNotSeen = 0
        default:break
        }
        
        item.badgeValue = nil
    }
    
}
